<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
            v-model="queryParams.brandName"
            placeholder="请输入品牌名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['shangpin:brand:add']"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Refresh"
            @click="resetQuery"
        >刷新</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌名称" align="left" prop="brandName" />
      <el-table-column label="品牌图标" align="left" prop="brandLogo">
        <template #default="scope">
          <el-image 
            v-if="scope.row.brandLogo" 
            :src="scope.row.brandLogo" 
            style="width: 50px; height: 50px; object-fit: contain;"
            :preview-src-list="[scope.row.brandLogo]"
          />
          <span v-else>暂无图标</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 'enabled'" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            type="warning" 
            size="small" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['shangpin:brand:edit']"
            style="margin-right: 8px; padding: 6px"
          >
            编辑
          </el-button>
                     <el-button 
             :type="scope.row.status === 'enabled' ? 'danger' : 'success'"
             size="small" 
             @click="handleToggleStatus(scope.row)" 
             v-hasPermi="['shangpin:brand:edit']"
             style="margin-right: 8px; padding: 6px"
           >
             {{ scope.row.status === 'enabled' ? '禁用' : '启用' }}
           </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['shangpin:brand:remove']"
            style="border: 1px solid #dcdfe6; background-color: #fff; color: #606266; border-radius: 4px; padding: 6px"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商品品牌对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="brandRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="品牌名称" prop="brandName">
          <el-input v-model="form.brandName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌图标" prop="brandLogo">
          <el-input v-model="form.brandLogo" placeholder="请输入品牌图标URL" />
          <el-button 
            v-if="form.brandLogo" 
            type="primary" 
            size="small" 
            style="margin-top: 8px;"
            @click="previewImage"
          >
            预览图片
          </el-button>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch
            v-model="form.status"
            active-value="enabled"
            inactive-value="disabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="submitForm">提交</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Brand">
import { listBrand, getBrand, delBrand, addBrand, updateBrand } from "@/api/shangpin/brand"

const { proxy } = getCurrentInstance()

const brandList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    brandName: null,
  },
  rules: {
    brandName: [
      { required: true, message: "品牌名称不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询商品品牌列表 */
function getList() {
  loading.value = true
  listBrand(queryParams.value).then(response => {
    brandList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    creator: null,
    createTime: null,
    isDeleted: null,
    updater: null,
    updateTime: null,
    brandLogo: null,
    brandName: null,
    status: null
  }
  proxy.resetForm("brandRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品品牌"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBrand(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商品品牌"
  })
}

/** 切换状态按钮操作 */
function handleToggleStatus(row) {
  const statusText = row.status === 'enabled' ? '禁用' : '启用'
  const newStatus = row.status === 'enabled' ? 'disabled' : 'enabled'
  
  proxy.$modal.confirm(`是否确认${statusText}商品品牌"${row.brandName}"？`).then(function() {
    const updateData = {
      id: row.id,
      status: newStatus,
      brandName: row.brandName,
      brandLogo: row.brandLogo
    }
    return updateBrand(updateData)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess(`${statusText}成功`)
  }).catch(() => {})
}

/** 预览图片 */
function previewImage() {
  if (form.value.brandLogo) {
    const h = proxy.$createElement
    proxy.$msgbox({
      title: '图片预览',
      message: h('div', { style: 'text-align: center;' }, [
        h('img', {
          src: form.value.brandLogo,
          style: 'max-width: 100%; max-height: 300px; object-fit: contain;'
        })
      ]),
      showCancelButton: false,
      confirmButtonText: '确定'
    })
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["brandRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBrand(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBrand(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商品品牌编号为"' + _ids + '"的数据项？').then(function() {
    return delBrand(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>

<style scoped>
.el-button {
  border-radius: 4px;
}
</style>
